//
//  dump.c
//  ipa_dumper491
//
//  Created by philip on 12/9/15.
//  Copyright © 2015 7659. All rights reserved.
//

#include "dump.h"

#include <xpc/xpc.h>
#import "SSZipArchive.h"


#define DCIM_PATH @"/var/mobile/Media/DCIM"

int dump(const char* src, const char* dest)
{
    xpc_connection_t connect = NULL;
    xpc_object_t event = NULL;
    xpc_object_t ret = NULL;
    
    event = xpc_dictionary_create(NULL,NULL,0);
    xpc_dictionary_set_int64(event,"operation",4);
    xpc_dictionary_set_int64(event,"transactionID",4);
    xpc_dictionary_set_string(event,"destSubdir", dest);
    xpc_dictionary_set_string(event,"srcPath", src);
    
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    connect = xpc_connection_create_mach_service("com.apple.PersistentURLTranslator.Gatekeeper",NULL,0);
    xpc_connection_set_event_handler(connect,^(xpc_object_t object)
                                     {
                                         NSLog(@"Done~!");
//                                         xpc_reply(object);
                                     });
    
    xpc_connection_resume(connect);
    ret = xpc_connection_send_message_with_reply_sync(connect,event);
    
    return xpc_dictionary_get_bool(ret, "success");
}

NSString* generateRelativePath(NSString* dest, NSString* current)
{
    NSArray* destArray = [dest componentsSeparatedByString:@"/"];
    NSArray* currentArray = [current componentsSeparatedByString:@"/"];

    unsigned long minCount = MIN([destArray count], [currentArray count]);
    int depth = 0;
    for ( int i = 0; i < minCount; i++) {
        if (NO == [[destArray objectAtIndex:i] isEqualToString:[currentArray objectAtIndex:i]]) {
            depth = i;
            break;
        }
    }
    
    NSMutableArray* resultArray = [[NSMutableArray alloc] init];
    for (int n = 0;  n < [currentArray count] - depth; n++) {
        [resultArray addObject:@".."];
    }
    
    [resultArray addObjectsFromArray:[destArray subarrayWithRange:NSMakeRange(depth, [destArray count] - depth)]];
   
    NSString* result = [NSString pathWithComponents:resultArray];
    return result;
}

int dumpIPA(NSString* path, NSString* ipaName)
{
    NSString* payloadPath = [NSString stringWithFormat:@"%@/Payload", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];
    if ([[NSFileManager defaultManager] fileExistsAtPath:payloadPath]) {
        [[NSFileManager defaultManager] removeItemAtPath:payloadPath error:nil];
    }
    
    [[NSFileManager defaultManager] createDirectoryAtPath:payloadPath attributes:nil];
    
    NSString* srcPath = [path substringFromIndex:strlen("file:///private")];
    NSString* appName = [srcPath lastPathComponent];
    
    NSString* destPath = [NSString stringWithFormat:@"%@/%@", payloadPath, appName];
    NSString* destRelativePath = generateRelativePath(destPath, DCIM_PATH);
    //copy from dest to self's document
    int success = dump([srcPath UTF8String], [destRelativePath UTF8String]);
    if (success) {
        //do zip
        success = [SSZipArchive createZipFileAtPath:[NSString stringWithFormat:@"%@/%@.ipa", [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"], ipaName] withContentsOfDirectory:[destPath stringByDeletingLastPathComponent] keepParentDirectory:YES];
        
        //copy back
        success = dump([destPath UTF8String], [generateRelativePath(srcPath, DCIM_PATH) UTF8String]);
    }
    
    [[NSFileManager defaultManager] removeItemAtPath:payloadPath error:nil];
    
    return success;
}